package com.caiheng.api.controller.platform;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.entity.platform.AdBanner;
import com.caiheng.api.entity.sys.SysDictData;
import com.caiheng.api.entity.titlemenu.TitleMenu;
import com.caiheng.api.entity.titlemenu.TitleMenuSection;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.service.platfom.AdBannerService;
import com.caiheng.api.service.sys.SysDictDataService;
import com.caiheng.api.service.titlemenu.TitleMenuSectionService;
import com.caiheng.api.service.titlemenu.TitleMenuService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.util.GsonResultBean;
import com.caiheng.api.util.Tools;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/titleMenu")//url:模块/资源/{}/细分
public class TitleMenuController extends BaseController{
    @Resource
    private TitleMenuService titleMenuService;
    @Resource
    private TitleMenuSectionService titleMenuSectionService;
    @Resource
    private SysDictDataService sysDictDataService;
    @Resource
    private AdBannerService adBannerService;
    @Resource
    private UserService userService;

    @Value("${web.imgPrefixOss}")
    private String imgPrefix;//图片前缀

    /**
     * 商品页 列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/service")
    public JSONObject service(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<String, Object>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int menu_type = jsonRequest.containsKey("menu_type") ? jsonRequest.getInt("menu_type") : 0;
            String service_type = jsonRequest.containsKey("service_type") ? jsonRequest.getStr("service_type") : null;

            QueryWrapper<SysDictData> qw = new QueryWrapper<>();
            qw.eq("dict_type","service_type");
            if(StrUtil.isNotEmpty(service_type)){
                qw.eq("dict_value","property");
            }

            qw.eq("status",0);
            qw.eq("remark","1");
            qw.orderByAsc("dict_sort");

            List<SysDictData> list = sysDictDataService.list(qw);
            if(CollUtil.isNotEmpty(list)){
                for (SysDictData sysDictData : list){
                    QueryWrapper<TitleMenu> qwMenu = new QueryWrapper<>();
                    qwMenu.eq("category_type",sysDictData.getDictValue());
                    qwMenu.eq("state",0);
                    qwMenu.orderByAsc("sort");
                    List<TitleMenu> menus = titleMenuService.list(qwMenu);
                    if(CollUtil.isNotEmpty(menus)){
                        for(TitleMenu titleMenu : menus){
                            if(StrUtil.isNotEmpty(titleMenu.getLinkLogo())){
                                titleMenu.setLinkLogo(imgPrefix + titleMenu.getLinkLogo());
                            }
                        }
                    }
                    sysDictData.setMenus(menus);
                }
            }
            map.put("menus",list);
//            //2. 内容列表
//            QueryWrapper<TitleMenu> qw = new QueryWrapper<>();
//            qw.eq("state",0);
//            qw.eq("menu_type",menu_type);
//            qw.eq("is_more_link",0);
//            qw.orderByAsc("sort");
//            List<TitleMenu> menus = titleMenuService.list(qw);
//            if(CollUtil.isNotEmpty(menus)){
//                for(TitleMenu titleMenu : menus){
//                    if(StrUtil.isNotEmpty(titleMenu.getLinkLogo())){
//                        titleMenu.setLinkLogo(imgPrefix + titleMenu.getLinkLogo());
//                    }
//                }
//            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     *  纯 菜单列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/menu/list")
    public JSONObject menuList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            String service_type = jsonRequest.containsKey("service_type") ? jsonRequest.getStr("service_type") : "";


            Map<String,Object> map = new HashMap<>();
            //2. 内容列表
            List<TitleMenu> listMenu = titleMenuService.selectBySpecial(service_type, null);
            map.put("listMenu",listMenu);
            map.put("menuRowCount",2);//每行显示的数量

            QueryWrapper<SysDictData> qw = new QueryWrapper<>();
            qw.eq("dict_type","service_type");
            qw.eq("dict_value",service_type);
            SysDictData sysDictData = sysDictDataService.selectDictData("service_type",service_type);
            if(sysDictData!=null){
                if(StrUtil.isNotEmpty(sysDictData.getAttachValue())){
                    map.put("menuRowCount", Integer.parseInt(sysDictData.getAttachValue()));//每行显示的数量
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",listMenu.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.toString(), e);
        }
        return result;
    }

    /**
     * 商品页 列表
     * @param
     * @throws Exception
     */
    @PostMapping(value = "/list")
    public JSONObject indexPage(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<String, Object>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int title_menu_id = jsonRequest.containsKey("title_menu_id") ? jsonRequest.getInt("title_menu_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 20;
            String platform = jsonRequest.containsKey("platform") ? jsonRequest.getStr("platform") : "wxmini";

            User user = userService.findById(user_id);

            //2. 内容列表
            List<TitleMenuSection> sections = titleMenuSectionService.selectByMenuId(user,title_menu_id,platform,pageIndex,pageSize);
            map.put("sections",sections);

            QueryWrapper<AdBanner> qw = new QueryWrapper<>();
            qw.eq("state",0);
            qw.eq("ad_type",4);
            qw.orderByAsc("sort");
            List<AdBanner> banners = adBannerService.list(qw);
            if(CollUtil.isNotEmpty(banners)){
                banners.forEach(banner->{
                    if(StrUtil.isNotEmpty(banner.getImgUrl())){
                        banner.setImgUrl(imgPrefix + banner.getImgUrl());
                    }
                });
            }
            map.put("banners",banners);

            TitleMenu titleMenu = titleMenuService.findById(title_menu_id);
            if(titleMenu!=null){
                map.put("titleMenu",titleMenu);
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",sections.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.toString(), e);
        }
        return result;
    }
}
